package com.sweet.entity;


import io.vertx.core.json.JsonObject;

public class TokenObj {
  private final String token;
  private final long time;
  private final long expiredTime = 1000L * 60 * 60 * 24 * 7;
  private final User user;

  public TokenObj(String token, Long time, User user) {
    this.token = token;
    this.time = time == null ? System.currentTimeMillis() : time;
    this.user = user;
  }

  public String getToken() {
    return token;
  }

  public long getTime() {
    return time;
  }

  public User getUser() {
    return user;
  }

  public String toJson() {
    return new JsonObject().put("token", token).put("time", time).put("user", user.toJson().encode()).encode();
  }

  public boolean expired() {
    return System.currentTimeMillis() - this.time >= expiredTime;
  }

  public static TokenObj fromJson(String s) {
    JsonObject jsonObject = new JsonObject(s);
    JsonObject user = jsonObject.getJsonObject("user");
    return new TokenObj(jsonObject.getString("token"), jsonObject.getLong("time"), user.mapTo(User.class));
  }

  @Override
  public String toString() {
    return "TokenObj{" +
            "token='" + token + '\'' +
            ", time=" + time +
            '}';
  }
}
